package day12.homework.project4;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.junit.Test;

import java.io.*;
import java.util.List;

public class Demo {
    @Test
    public void test1() throws IOException, Exception {
        //读取note.xml
        InputStream is = new FileInputStream("src\\main\\resources\\employees.xml");
        //创建解析对象
        SAXReader reader = new SAXReader();
        //读取输入流返回文档
        Document doc = reader.read(is);

        Element toEle = doc.getRootElement();

        Element el = toEle.addElement("employee");
        el.addAttribute("id", "3");
        el.addElement("name").setText("王五");
        el.addElement("age").setText("20");
        el.addElement("sex").setText("男");
        el.addElement("address").setText("深圳");


        //4 利用IO流OutputStream类
        OutputStream os = new FileOutputStream("src\\main\\resources\\employees.xml");


        //带格式的输出xml
        XMLWriter writer = new XMLWriter(os, OutputFormat.createPrettyPrint());
        writer.write(doc);

        System.out.println("文档写好了...");

    }

    @Test
    public void test2() throws IOException, Exception {
        //读取note.xml
        InputStream is = new FileInputStream("src\\main\\resources\\employees.xml");
        //创建解析对象
        SAXReader reader = new SAXReader();
        //读取输入流返回文档
        Document doc = reader.read(is);

        Element toEle = doc.getRootElement();

        List<Element> els = toEle.elements();

        for (Element el : els) {
            if (el.attributeValue("id").equals("1")){
                el.detach();
            }
        }

        //4 利用IO流OutputStream类
        OutputStream os = new FileOutputStream("src\\main\\resources\\employees.xml");

        //带格式的输出xml
        XMLWriter writer = new XMLWriter(os, OutputFormat.createPrettyPrint());
        writer.write(doc);

        System.out.println("文档写好了...");

    }

    @Test
    public void test3() throws IOException, Exception {
        //读取note.xml
        InputStream is = new FileInputStream("src\\main\\resources\\employees.xml");
        //创建解析对象
        SAXReader reader = new SAXReader();
        //读取输入流返回文档
        Document doc = reader.read(is);

        Element toEle = doc.getRootElement();

        List<Element> els = toEle.elements();

        for (Element el : els) {
            if (el.attributeValue("id").equals("2")){
                el.element("name").setText("张三丰");
            }
        }

        //4 利用IO流OutputStream类
        OutputStream os = new FileOutputStream("src\\main\\resources\\employees.xml");

        //带格式的输出xml
        XMLWriter writer = new XMLWriter(os, OutputFormat.createPrettyPrint());
        writer.write(doc);

        System.out.println("文档写好了...");
    }
}
